package com.fancy.learncenter.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonClassListBean;
import com.fancy.learncenter.bean.MySelfDataBean;
import com.fancy.learncenter.bean.UnMsgDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.CartoonChildHomeActivity;
import com.fancy.learncenter.ui.activity.EveryDayWorkActivity;
import com.fancy.learncenter.ui.activity.EverydayListenSpeekActivity;
import com.fancy.learncenter.ui.activity.MyBusinessCooperationActivity;
import com.fancy.learncenter.ui.activity.MyCollectionActivity;
import com.fancy.learncenter.ui.activity.MyMsgActivity;
import com.fancy.learncenter.ui.activity.MyQRActivity;
import com.fancy.learncenter.ui.activity.MyRecorderAudioActivity;
import com.fancy.learncenter.ui.activity.MySchoolActivity;
import com.fancy.learncenter.ui.activity.MyServiceActivity;
import com.fancy.learncenter.ui.activity.SettingInfoActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.jph.takephoto.app.TakePhotoFragment;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.utils.NetUtil.getResResult;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyselfFragment extends TakePhotoFragment {

    View rootView;
    @Bind(R.id.gridView)
    RecyclerView gridView;
    @Bind(R.id.setting_icon)
    ImageView settingIcon;
    @Bind(R.id.simpleDraweeView)
    SimpleDraweeView simpleDraweeView;
    @Bind(R.id.login_status)
    TextView loginStatus;
    @Bind(R.id.top_LL)
    RelativeLayout topLL;
    @Bind(R.id.ll)
    LinearLayout ll;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.unMsg)
    TextView unMsg;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_myself, container, false);
        ButterKnife.bind(this, rootView);
        initGridView();

        return rootView;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (Constant.isLogin) {
            simpleDraweeView.setImageURI(LoginUserSharePrefernce.getHeaderPath());
            loginStatus.setText(LoginUserSharePrefernce.getName());
            name.setText(LoginUserSharePrefernce.getMobile());

            getMsgData();
        } else {
            simpleDraweeView.setImageURI("");
            name.setText("");
            loginStatus.setText("未登录");
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void initGridView() {
        List<MySelfDataBean> data = new ArrayList<>();
        MySelfDataBean bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_activity);
        bean.setTitle("我的活动");
        data.add(bean);
        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.music_icon);
        bean.setTitle("我的录音");
        data.add(bean);
        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_collection);
        bean.setTitle("我的收藏");
        data.add(bean);


        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_club);
        bean.setTitle("我的红包");
        data.add(bean);
        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_order);
        bean.setTitle("我的订单");
        data.add(bean);

        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_cart);
        bean.setTitle("我的购物车");
        data.add(bean);

//        bean = new MySelfDataBean();
//        bean.setIconRes(R.mipmap.my_borrow_qrcode);
//        bean.setTitle("借阅二维码");
//        data.add(bean);
//        bean = new MySelfDataBean();
//        bean.setIconRes(R.mipmap.my_message);
//        bean.setTitle("消息通知");
//        data.add(bean);
        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_business);
        bean.setTitle("商务合作");
        data.add(bean);
        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_contant);
        bean.setTitle("我的客服");
        data.add(bean);

        bean = new MySelfDataBean();
        bean.setIconRes(R.mipmap.my_role);
        bean.setTitle("我的身份");
        data.add(bean);

        bean = new MySelfDataBean();
        data.add(bean);
        bean = new MySelfDataBean();
        data.add(bean);
        bean = new MySelfDataBean();
        data.add(bean);


        GridLayoutManager manager = new GridLayoutManager(getActivity(), 4);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.HORIZONTAL);
        itemDecoration.setDrawable(getResources().getDrawable(R.drawable.myself_item_border));
//        gridView.addItemDecoration(itemDecoration);
        gridView.setLayoutManager(manager);

        gridView.setAdapter(new CommonRecycleViewAdapter<MySelfDataBean>(getActivity(), R.layout.fragment_myself_grid_item, data) {
            @Override
            public void bindView(CustomViewHold customViewHold, MySelfDataBean item, final int position) {
                ImageView icon = customViewHold.getView(R.id.icon);
                icon.setImageResource(item.getIconRes());

                TextView title = customViewHold.getView(R.id.title);
                title.setText(item.getTitle());

                customViewHold.getRoorView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent;
                        switch (position) {
                            case 0:
                                //    我的活动
                                intent = new Intent(getActivity(), MallCommonH5Activity.class);
                                intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallActivity());
                                getActivity().startActivity(intent);
                                break;
                            case 1:
                                //    我的录音
                                intent = new Intent(getActivity(), MyRecorderAudioActivity.class);
                                getActivity().startActivity(intent);
                                break;
                            case 2:
                                //    我的收藏
                                intent = new Intent(getActivity(), MyCollectionActivity.class);
                                getActivity().startActivity(intent);
                                break;
//                            case 3:
//                                //    学校
//                                intent = new Intent(getActivity(), EverydayListenSpeekActivity.class);
//                                getActivity().startActivity(intent);
//                                break;
                            case 3:
                                //    我的红包
                                intent = new Intent(getActivity(), MallCommonH5Activity.class);
                                intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallRedPacket());
                                getActivity().startActivity(intent);
                                break;
                            case 4:
                                //    我的订单
                                intent = new Intent(getActivity(), MallCommonH5Activity.class);
                                intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallOrder());
                                getActivity().startActivity(intent);
                                break;
                            case 5:
                                //    购物车
                                intent = new Intent(getActivity(), MallCommonH5Activity.class);
                                intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallShopCart());
                                getActivity().startActivity(intent);
                                break;
//                            case 5:
//                                //    借阅二维码
//                                intent = new Intent(getActivity(), MyQRActivity.class);
//                                getActivity().startActivity(intent);
////                                SharePopupWindow popupWindow = new SharePopupWindow(getActivity(), ll, R.layout.popupwindow_share, Gravity.CENTER);
////                                popupWindow.showPopupWindow();
//                                break;
//                            case 6:
//                                //    消息通知
//                                intent = new Intent(getActivity(), MyMsgActivity.class);
//                                getActivity().startActivity(intent);
//                                break;
                            case 6:
                                //    商务合作
                                intent = new Intent(getActivity(), MyBusinessCooperationActivity.class);
                                getActivity().startActivity(intent);
                                break;
                            case 7:
                                //    联系客服
//                                ToastUtil.show("H5开发");
                                intent = new Intent(getActivity(), MyServiceActivity.class);
                                getActivity().startActivity(intent);
                                break;
                            case 8:
                                //    联系客服
//                                intent = new Intent(getActivity(), MyServiceActivity.class);
//                                getActivity().startActivity(intent);

                                LogUtil.MyLog("gettStudentRole", "============");


                                if (SPUtils.gettStudentRole()) {
                                    ToastUtil.show("我的老师身份");

                                    LogUtil.MyLog("putStudentRole", "======sadds======");
                                    SPUtils.putStudentRole(false);

                                    SPUtils.putTeacherRole(true);

                                } else if (SPUtils.gettTeacherRole()) {

                                    LogUtil.MyLog("putStudentRole", "======asdasdasd======");
                                    SPUtils.putStudentRole(true);

                                    SPUtils.putTeacherRole(false);

                                    ToastUtil.show("我的学生身份");
                                }


                                break;

//                            case 10:
//                                //    我的课程
//                                intent = new Intent(getActivity(), MallCommonH5Activity.class);
//                                intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMyLesson());
//                                getActivity().startActivity(intent);
//                                break;

                        }
                    }
                });
            }
        });
    }

    @OnClick({R.id.setting_icon, R.id.simpleDraweeView, R.id.my_borrow_qrcode_layout, R.id.my_message_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_icon:
                Intent intent = new Intent(getActivity(), SettingInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.simpleDraweeView:
//                PermissionCustomManager manager = new PermissionCustomManager(getActivity(), Manifest.permission.RECORD_AUDIO, new PermissionCustomManager.OnPermissionListener() {
//                    @Override
//                    public void onAccept() {
//                        File file = new File(Environment.getExternalStorageDirectory(), Constant.HEADER_CUT_PATH + System.currentTimeMillis() + ".jpg");
//                        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
//                        Uri imageUri = Uri.fromFile(file);
//                        getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());
//                    }
//                });
                break;

            case R.id.my_borrow_qrcode_layout:
                //    借阅二维码
                intent = new Intent(getActivity(), MyQRActivity.class);
                getActivity().startActivity(intent);

                break;

            case R.id.my_message_layout:

                //    消息通知
                intent = new Intent(getActivity(), MyMsgActivity.class);
                getActivity().startActivity(intent);

                break;
        }
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        simpleDraweeView.setImageURI("file://" + result.getImage().getOriginalPath());
    }

    private CropOptions getCropOptions() {
        int height = 50;
        int width = 50;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }


    private void getMsgData() {
        HttpMehtod.getInstance().getUnMessage(new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<UnMsgDataBean> baseBean = Utils.fromJsonObject(getResResult(responseBodyResponse), UnMsgDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<UnMsgDataBean>() {
                    @Override
                    public void success(UnMsgDataBean dataBean) {
                        Log.d("getMsgData", "===============getMsgData======");
                        unMsg.setVisibility(View.VISIBLE);
                        if (dataBean.getResult() >= 99) {
                            unMsg.setText("99+");
                        } else if (dataBean.getResult() == 0) {
                            unMsg.setVisibility(View.INVISIBLE);
                        } else {
                            unMsg.setText(dataBean.getResult() + "");
                        }

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }

            @Override
            public void onCompleted() {
                super.onCompleted();
            }
        });
    }



}
